package lex.explorer.directory;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.filechooser.FileSystemView;

import org.lex.swing.tree.LazyMutableTreeNode;


public class FileTreeNode extends LazyMutableTreeNode implements Comparable<FileTreeNode>
{
	private static FileTreeNode[] EMPTY_ARRAY = new FileTreeNode[0];
	private static FileSystemView fsv = FileSystemView.getFileSystemView();

	public FileTreeNode( File file )
	{
		super( file );
	}

	protected void loadChildren()
	{
		FileTreeNode[] nodes = getChildren();
		for( FileTreeNode node : nodes )
			this.add( node );
	}

	private FileTreeNode[] getChildren()
	{
		// File[] files = fsv.getFiles( getFile(), false );
		File[] files = this.getFile().listFiles();
		if( null == files || 0 == files.length )
			return EMPTY_ARRAY;
		// ===============================
		ArrayList<FileTreeNode> nodes = new ArrayList<FileTreeNode>();
		// keep only directories, no "file" in the tree.
		for( File file : files )
			if( true == file.isDirectory() )
				nodes.add( new FileTreeNode( file ) );
		// sort directories, FileTreeNode implements Comparable
		FileTreeNode[] result = nodes.toArray( EMPTY_ARRAY );
		Arrays.sort( result );
		return result;
	}

	public File getFile()
	{
		return (File) getUserObject();
	}

	public String toString()
	{
		return fsv.getSystemDisplayName( this.getFile() );
	}

	public int compareTo( FileTreeNode o )
	{
		return getFile().compareTo( o.getFile() );
	}
}
